//
//  ST_PEImagePickerController.swift
//  btvideo
//
//  Created by mac on 2020/1/13.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SnapKit
import TZImagePickerController
import SwifterSwift
import SwiftyAttributes


//暂时弃用
class ST_PEImagePickerController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = Color.white
        
        view.addSubview(header)
        header.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.height.equalTo(44)
            make.top.equalToSuperview().offset(ST_JVStatusBarHeight)
        }
        
        
        view.addSubview(media_preview)
        media_preview.snp.makeConstraints { (make) in
            make.top.equalTo(header.snp.bottom)
            make.right.left.equalToSuperview()
            make.height.equalTo(media_preview.snp.width).dividedBy(375/300.0)
        }
        media_preview.addSubview(preview_image_view)
        preview_image_view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.top.equalTo(media_preview.snp.bottom).offset(20)
            make.left.right.bottom.equalToSuperview()
        }
        
        view.addSubview(empty_label)
        empty_label.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.centerY.equalTo(collectionView).offset(-40)
        }
       
        
        self.header.select_album_closure = {[weak self] in
            
            guard let strongSelf  = self else{return}
             
            strongSelf.addChild(strongSelf.select_album_controller)
            strongSelf.view.addSubview(strongSelf.select_album_controller.view)
            strongSelf.select_album_controller.view.snp.makeConstraints { (make) in
                make.left.right.bottom.equalToSuperview()
                make.top.equalTo(strongSelf.header.snp.bottom)
            }
        }
        
        self.header.cancel_select_album_closure = {[weak self] in
            
            self?.select_album_controller.removeFromParent()
            self?.select_album_controller.view.removeFromSuperview()
            
        }
        
        self.header.finished_closure = { [weak self] in
        }
        
        
        TZImageManager().pickerDelegate = self
        
        if !TZImageManager().authorizationStatusAuthorized(){
            
            if PHPhotoLibrary.authorizationStatus() == .notDetermined{
                
                authorized_timer = Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: #selector(observe_authrization_status_change), userInfo: nil, repeats: false)
                
            }else{
                user_denied_authorization()
            }
        }else{
            
            switch_to(album: nil)
        }
        
    }
    
    
//    MARK: - Method
    fileprivate func user_denied_authorization(){
        
        denied_view.removeFromSuperview()
        view.addSubview(denied_view)
        denied_view.snp.makeConstraints { (make) in
            make.edges.equalTo(collectionView)
        }
    }
    
    func switch_to(album:TZAlbumModel?){
        
        denied_view.removeFromSuperview()
        
        if let exist = album {
            
            self.current_album = exist
            
            self.header.update_album_name(name: exist.name)
            
            self.fetch_photos()
            
            return
        }
        
        self.header.update_album_name(name: "所有照片")
        
        TZImageManager().getCameraRollAlbum(true, allowPickingImage: true, needFetchAssets: false) { (reAlbum) in
            
            self.current_album = reAlbum
            
            self.fetch_photos()
        }
        
        
    }
    
    
    @objc func observe_authrization_status_change(){
        
        authorized_timer?.invalidate()
        authorized_timer = nil
        
        if PHPhotoLibrary.authorizationStatus() == .notDetermined{
            
            authorized_timer = Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: #selector(observe_authrization_status_change), userInfo: nil, repeats: false)
            
            return
        }
        
        if TZImageManager().authorizationStatusAuthorized(){
            
            switch_to(album: nil)
        }else{
            user_denied_authorization()
        }
    }
    
    fileprivate func fetch_photos(){
        
      
        
        guard let result = current_album?.result else{ return }
        
        
        TZImageManager().getAssetsFrom(result, allowPickingVideo: true, allowPickingImage: true) { (list) in
            

            guard let array =  list else{
                return
            }
                       
            print("多少张图片呢？",array.count)
            
            self.data_array = array.filter({ (zAsset) -> Bool in
                
                if zAsset.type == TZAssetModelMediaType.init(3),let timeLength = zAsset.timeLength{
                    
                    let timeArray = timeLength.components(separatedBy: ":")
                    
                    var timeSeconds = 0.float
                    for (idx,item) in timeArray.reversed().enumerated(){
                        if let value = item.float(){
                            timeSeconds += value * powf(60, idx.float)
                        }
                    }
                    if  timeSeconds < 5 || timeSeconds > 60{
                        return false
                    }
//                    let duration = timeLength.nsString.replacingOccurrences(of: ":", with: ".")
                    
//                    if let d = duration.float() , d < 0.05 && d > 1{
//                        return false
//                    }
                }
                
                return true
            })
           
           self.collectionView.reloadData()
            
            if array.count < 1{
                
                self.empty_label.isHidden = false
                
                self.empty_label.attributedText = self.display_video ? self.empty_video_attribute : self.empty_photos_attribute
                
            }else{
                
                self.empty_label.isHidden = true
                
                
                self.selectedMedia(indexPath: IndexPath.init(row: 0, section: 0))
            }
            
        }
    }
//    MARK: - Selected Properties
    fileprivate var selectedImage:UIImage?
    
    fileprivate var selectedUrl:URL?
//    MARK: - Properties
    var close_closure:(()->())?
    
    var picker_style = ST_JVAlbumPickerStyle.all
    
    weak var presentedCtr:UIViewController?
    
    fileprivate lazy var header:ST_PEImagePickerHeaderView = {
       let control = ST_PEImagePickerHeaderView()
        control.close_closure = {[weak self] in
            self?.close_closure?()
        }
        return control
    }()
    
    fileprivate lazy var select_album_controller:ST_JVAlbumListController = {
       let control = ST_JVAlbumListController()
        control.selectedAlbumClosure = {[weak self] ab in
            self?.switch_to(album: ab)
            self?.header.set_center_btn_state_normal()
        }
        return control
    }()
    
    fileprivate lazy var display_video:Bool = {
        if picker_style == .image{
            return false
        }
        return true
    }()
    
    fileprivate var current_album:TZAlbumModel?
    
    fileprivate var data_array = [TZAssetModel]()
    
    fileprivate var authorized_timer:Timer?
    
    fileprivate let rowCount = 4
    
    fileprivate let minimum_spacing = 15.cgFloat
    
    fileprivate lazy var itemWidth:CGFloat = {
        
        return (ST_JVScreenWidth-minimum_spacing*(rowCount-1).cgFloat-section_right_edge*2)/rowCount.cgFloat
        
    }()
    
    fileprivate lazy var section_right_edge:CGFloat = {
        return 15
    }()
    
    fileprivate lazy var denied_view: ST_JVDeniedPhotoAuthorizationView = ST_JVDeniedPhotoAuthorizationView()
    
    fileprivate lazy var media_preview:UIView = {
       let control = UIView()
//        control.backgroundColor = Color.random
        return control
    }()
    
    fileprivate lazy var preview_image_view:UIImageView = {
       let control = UIImageView()
        control.contentMode = UIView.ContentMode.scaleAspectFit
        return control
    }()
    
    fileprivate lazy var collectionView: UICollectionView = {
        
        let layout = UICollectionViewFlowLayout()
//        layout.scrollDirection = UICollectionView.ScrollDirection.horizontal
        layout.itemSize = CGSize.init(width: itemWidth, height: itemWidth)
        layout.sectionInset = UIEdgeInsets.init(top: 0, left: section_right_edge, bottom: BTSafeAreaBottom + 20, right: section_right_edge)
        //        layout.scrollDirection = .horizontal
        layout.minimumLineSpacing = minimum_spacing
        layout.minimumInteritemSpacing = minimum_spacing

        let collection = UICollectionView(frame: .zero, collectionViewLayout: layout)
        
        collection.backgroundColor = Color.white
        
        collection.alwaysBounceVertical = true
        
        collection.register(cellWithClass: TZAssetCell.self)
        //        collection.alwaysBounceVertical = true
        collection.delegate = self
        
        collection.dataSource = self
        
        return collection
    }()
    //    MARK: -  player properties
    //    播放中
    fileprivate var playing = false

    fileprivate var player:AVPlayer?

    fileprivate var time_observer:Any?

    fileprivate var playerItem:AVPlayerItem?

//    fileprivate var playerLayer:AVPlayerLayer?
    
    fileprivate var avPlayerView:ST_PairsAVPlayerView?
    
    fileprivate var currPalyIdx:Int?
    //    MARK: - player Method
    fileprivate func play(asset:AVAsset) {
        
        self.selectedUrl = (asset as? AVURLAsset)?.url
     
        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
        }catch{
            print("AVAudioSession.Category.playback Error")
        }
        
        let playerItem = AVPlayerItem.init(asset: asset)
        
        self.playerItem = playerItem

        //创建ACplayer：负责视频播放
        self.player = AVPlayer.init(playerItem: playerItem)
        self.player?.isMuted = true
        self.player?.rate = 1.0//播放速度 播放前设置
        //创建显示视频的图层
        
        
        avPlayerView = ST_PairsAVPlayerView()
        self.media_preview.addSubview(avPlayerView!)
        
//        avPlayerView?.backgroundColor = UIColor.red
        
        avPlayerView?.snp.makeConstraints({ (make) in
            make.edges.equalToSuperview()
        })
        
        guard let castedLayer = avPlayerView?.layer as? AVPlayerLayer else{
            return
        }
        
        castedLayer.player = self.player
        castedLayer.videoGravity = .resizeAspect
        
        guard let player = self.player else { return  }
        
        player.play()
        
        playing = true
        
    }
        
    fileprivate func stop(){
        
        self.selectedUrl = nil
        
        playing = false
        
//        guard let playerLayer = self.playerLayer else { return  }
//        playerLayer.removeFromSuperlayer()
//        self.playerLayer = nil
        
        guard let player = self.player else { return  }
        
        if  let timerObs = self.time_observer{
            player.removeTimeObserver(timerObs)
        }
        
        avPlayerView?.removeFromSuperview()
        avPlayerView = nil
        
        player.pause()
        
        
        
        self.player = nil
    }
    
    
//    MARK: - Empty View
    
    fileprivate lazy var empty_video_attribute:NSAttributedString = {
        return "相册中没有视频".withAttributes([Attribute.font(UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.regular)),Attribute.textColor(UIColor.init(hex: 0x000000)!)])
    }()
    
    fileprivate lazy var empty_photos_attribute:NSAttributedString = {
        return "相册中没有图片".withAttributes([Attribute.font(UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.regular)),Attribute.textColor(UIColor.init(hex: 0x000000)!)])
    }()
    
    fileprivate lazy var empty_label:UILabel = {
       let control = UILabel()
        control.isHidden = true
        control.textAlignment = .center
        return control
    }()
    
//    MARK: - Event
    
    func selectedMedia(indexPath:IndexPath){
        
        guard let curr = data_array[safe:indexPath.item] else { return }
        
        switch curr.type {
            
        case TZAssetModelMediaTypePhoto,TZAssetModelMediaTypeLivePhoto,TZAssetModelMediaTypePhotoGif:
            
            TZImageManager().getOriginalPhotoData(with: curr.asset) {[weak self] (data, info, f) in
                
                guard let d = data , let img = UIImage.init(data: d) else{
                    self?.selectedImage = nil
                    return
                }
                self?.stop()
                self?.preview_image_view.image = img
                self?.preview_image_view.isHidden = false
                self?.selectedImage = img
            }
            
            break
        case TZAssetModelMediaTypeVideo:
            
            self.selectedImage = nil
            
            let options = PHVideoRequestOptions()
            
            options.version = .original
            options.deliveryMode = .automatic
            options.isNetworkAccessAllowed = true
            
            
            PHCachingImageManager().requestAVAsset(forVideo: curr.asset, options: options) {[weak self] (avAsset, audioMix, info) in
                
                
                guard let ast = avAsset else{
                    
                    return
                }
                
                main_thread_execute {
                    
                    self?.selectedImage = nil
                    
                    self?.stop()
                    
                    self?.preview_image_view.isHidden = true
                    
                    self?.play(asset: ast)
                    
               }
                
            }
            
            break
        default:
            break
        }
        
    }

    
   
    
    func show_alert_with_title(title:String){
        
        let alert = UIAlertController.init(title: "提示", message: title, preferredStyle: UIAlertController.Style.alert)
        
        
        alert.addAction(title: "ok", style: UIAlertAction.Style.default, isEnabled: true) { (action) in
            
        }
        
        self.present(alert, animated: true, completion: nil)
        
    }
    

}

extension ST_PEImagePickerController:UICollectionViewDataSource,UICollectionViewDelegate{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return data_array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withClass: TZAssetCell.self, for: indexPath)
        
//        cell.photoDefImage = tz_image_picker_vc.photoDefImage;
//        cell.photoSelImage = tz_image_picker_vc.photoSelImage;
        
        let model = self.data_array[indexPath.row]
        
        cell.model = model
      
        cell.contentView.cornerRadius = 10
        
//        weak var weakCell = cell
//
//        weak var weakModel = model
        
//        cell.didSelectPhotoBlock = {[weak self] isSelected in
//
//            guard let strongSelf = self else { return  }
//
//            guard let strongModel = weakModel else { return  }
//
//            guard let strongCell = weakCell else { return  }
//        }
        
        
        return cell
    }
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        
        self.selectedMedia(indexPath: indexPath)
        
    }
    
}


extension ST_PEImagePickerController:TZImagePickerControllerDelegate{
    
    
    func is_asset_can_select(_ asset: PHAsset!) -> Bool {
        
        return true
    }
    
}

